import { Menu } from "antd"
import * as allIcons from '@ant-design/icons';

import { Link } from "react-router";
import { useSelector } from "react-redux";
import type { RootState } from "@/store";
// import { useSliceData } from "@/hooks/useSliceData";
import React, { useEffect, useMemo } from "react";

const SideMenu = () => {
    // 获取仓库数据
    const adminInfo = useSelector((state: RootState) => state.admin.adminInfo);
    // console.log('菜单中获取仓库数据', adminInfo);

    // const { getAdminInfoHook } = useSliceData();

    // useEffect(() => {
    //     getAdminInfoHook();
    // }, [])

    const menuData = useMemo(() => {
        if (adminInfo?.roleId?.permissions) {
            return mapMenus(adminInfo.roleId.permissions)
        }
        return [];
    }, [adminInfo])

    return (
        <Menu
            mode="inline"
            defaultSelectedKeys={['1']}
            defaultOpenKeys={['sub1']}
            style={{ height: '100%', borderRight: 0 }}
            items={menuData}
        />

    )
}

export default SideMenu;


// 递归处理菜单数据格式
function mapMenus(permissions: any): any {
    return permissions.reduce((prev, item) => {
        if (item.type == 'menu') {
            if (item.children) {
                // 将children中的button类型去掉
                const childrenData = mapMenus(item.children);

                if (childrenData.length > 0) {
                    return [
                        ...prev,
                        {
                            key: item.path,
                            label: item.title,
                            children: childrenData,
                            icon: item.icon ? React.createElement((allIcons as any)[item.icon]) : null
                        }
                    ]
                }
            }
            return [
                ...prev,
                {
                    key: item.path,
                    label: <Link to={item.path}>{item.title}</Link>,
                    icon: item.icon && React.createElement((allIcons as any)[item.icon])
                }
            ]
        }
        return prev;
    }, [])
}